package com.noble.meether.logic.common;

import android.support.v4.app.FragmentActivity;

import com.alibaba.fastjson.JSON;
import com.noble.glamour.bean.config.CommonConfig;
import com.noble.glamour.bean.my.GiftsList;
import com.noble.glamour.bean.settting.ContactBean;
import com.noble.glamour.module.local.chat.utils.MsgUtils;
import com.noble.glamour.module.logic.application.App;
import com.noble.glamour.module.logic.application.ModuleMgr;
import com.noble.glamour.module.logic.baseui.LoadingDialog;
import com.noble.glamour.module.logic.config.Constant;
import com.noble.glamour.module.logic.config.UrlParam;
import com.noble.glamour.module.logic.request.RequestComplete;
import com.noble.glamour.module.logic.request.RequestParam;
import com.noble.glamour.module.util.UIShow;
import com.noble.glamour.module.util.my.GiftHelper;
import com.noble.glamour.ui.user.paygoods.GoodsConstant;
import com.noble.library.dir.DirType;
import com.noble.library.log.PLogger;
import com.noble.library.log.PToast;
import com.noble.library.observe.ModuleBase;
import com.noble.library.observe.MsgMgr;
import com.noble.library.observe.MsgType;
import com.noble.library.utils.FileUtil;
import com.noble.meether.chat.ui.agora.act.bean.RtcComplainReasons;
import com.noble.meether.chat.ui.agora.model.EngineConfig;
import com.noble.meether.chat.ui.system.SysMessAct;
import com.noble.meether.chat.ui.system.bean.SysNotice;
import com.noble.meether.chat.ui.system.bean.SysNoticeList;
import com.noble.meether.chat.ui.system.store.DBNoticeCache;
import com.noble.meether.logic.common.bean.Setting;
import com.noble.meether.logic.common.bean.Updata;
import com.noble.meether.mail.ui.util.UserRelationStatus;
import com.noble.meether.pay.bean.Pay;
import com.noble.meether.pay.utils.PayAlipayUtils;
import com.noble.meether.pay.utils.PayWeixinUtils;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 通用，新版本
 * Created by Xy on 17/3/22.
 */
public class CommonMgr implements ModuleBase {
    private CommonConfig commonConfig;//服务器静态配置
    private ContactBean contactBean;//客服信息

    private GiftsList giftLists;//礼物信息
    private RtcComplainReasons complainReasons; // 投诉信息

    @Override
    public void init() {
    }

    @Override
    public void release() {
    }

    // ==============================  指派消息服务器 ===========================
    public void reqMsgServer() {
        ModuleMgr.getHttpMgr().reqGetNoCacheHttp(UrlParam.reqMsgServer, null, null);
    }

    private EngineConfig config() {
        return ModuleMgr.getRtcEnginMgr().getEngineConfig();
    }

    private static Setting setting;

    public Setting getSetting() {
        if (setting == null) {
            setting = new Setting();
        }
        return setting;
    }

    /**
     * 获取全局配置
     */
    public void reqSettingAll(RequestComplete complete) {
        reqSettingAll(-1, complete);
    }

    /**
     * 获取全局配置
     *
     * @param group 分组： 按需获取配置数据
     */
    public void reqSettingAll(int group, RequestComplete complete) {
        HashMap<String, Object> param = new HashMap<>();
        param.put("app_id", Constant.getAppId());
        param.put("group", group);
        ModuleMgr.getHttpMgr().reqGetAndCacheHttp(UrlParam.reqSettingAll, param, response -> {
            if (!response.isOk()) return;
            setting = (Setting) response.getBaseData();
            MsgMgr.getInstance().sendMsg(MsgType.MT_Setting_Suc, null);
        });
    }

    // ======================= 系统公告消息处理 ==========================
    private int idMax = 0;              // 本地记录最大消息ID
    private List<SysNotice> noticeList = new ArrayList<>();  // 公告列表

    public List<SysNotice> getNoticeList() {
        return noticeList;
    }

    public void getNoticeMsg() {
        try {
            noticeList.clear();
            ModuleMgr.getDbMgr().getNoticeCache().queryMsgList(new DBNoticeCache.DBNoticeCallback() {
                @Override
                public void onFailure(int code, String message) {
                    ModuleMgr.getCommonMgr().reqSysMessage(idMax, noticeComplete);
                }

                @Override
                public void onSuccess(List<SysNotice> data) {
                    if (data != null && data.size() > 0) {
                        idMax = data.get(data.size() - 1).getId();
                        noticeList.addAll(data);
                    }
                    ModuleMgr.getCommonMgr().reqSysMessage(idMax, noticeComplete);
                }
            });
        } catch (Exception e) {
            PLogger.printThrowable(e);
        }
    }

    private RequestComplete noticeComplete = response -> {
        if (response.isOk()) {
            SysNoticeList data = (SysNoticeList) response.getBaseData();

            if (data != null && data.getSysNoticeList().size() > 0) {
                Collections.reverse(data.getSysNoticeList());
                noticeList.addAll(data.getSysNoticeList());
                ModuleMgr.getDbMgr().getNoticeCache().insertMsgBatch(data.getSysNoticeList(), null);

                boolean instanceSysMess = App.getActivity() instanceof SysMessAct;
                if (!instanceSysMess) {  // 当前未处于系统公告页面
                    MsgUtils.handleNoticeUnread(data.getSysNoticeList().size());  // 增加角标
                    ModuleMgr.getNotifyMgr().vibrator();
                } else {
                    MsgMgr.getInstance().sendMsg(MsgType.MT_Refresh_Notice, null);
                }
                MsgMgr.getInstance().sendMsg(MsgType.MT_Msg_Notice, null);
            }
        }
    };

    /**
     * 获取系统公共消息
     *
     * @param idMax 本地记录的最大ID
     */
    private void reqSysMessage(int idMax, RequestComplete complete) {
        HashMap<String, Object> param = new HashMap<>();
        param.put("id_max", idMax);
        param.put("limit", 100);
        param.put("offset", 0);
        ModuleMgr.getHttpMgr().reqGetNoCacheHttp(UrlParam.reqSysMessage, param, complete);
    }

    // ======================= 系统公告消息处理 end ==========================

    /**
     * 反馈问题
     */
    public void reqFeedBack(String phone, String content, String imageJson, RequestComplete complete) {
        Map<String, Object> jsonMap = new HashMap<>();
        jsonMap.put("Telphone", phone);
        jsonMap.put("Content", content);
        jsonMap.put("Os", "android");
        jsonMap.put("ImageJson", imageJson);
        ModuleMgr.getHttpMgr().reqJsonNoCacheHttp(UrlParam.reqFeedBack, jsonMap, complete);
    }

    /**
     * 检查更新
     */
    public void reqNewVersion(final RequestComplete complete) {
        Map<String, Object> getParam = new HashMap<>();
        getParam.put("app_id", Constant.getAppId());
        getParam.put("os", 1);
        getParam.put("version", ModuleMgr.getAppMgr().getVerCode());
        ModuleMgr.getHttpMgr().reqGetNoCacheHttp(UrlParam.reqNewVersion, getParam, response -> {
            if (response.isOk()) {
                Updata updata = (Updata) response.getBaseData();
                if (updata == null) return;

                if (updata.isUpgrade()) { // 发现新版本
                    UIShow.showUpdateDialog((FragmentActivity) App.getActivity(), updata);
                }
            }
        });
    }

    /**
     * 发起支付
     *
     * @param payType     支付类型 默认1 微信支付 = 1 阿里支付 = 2
     * @param productType 商品类别 钻石=1 VIP=2
     */
    public void reqPayAdd(final int payType, int productType, int productCode, String subject, final RequestComplete complete) {
        LoadingDialog.show((FragmentActivity) App.getActivity(), "正在获取订单信息");
        Map<String, Object> postParam = new HashMap<>();
        postParam.put("type_pay", payType);
        postParam.put("type_product", productType);
        postParam.put("product_id", productCode);
        postParam.put("subject", subject);
        ModuleMgr.getHttpMgr().reqPostNoCacheHttp(UrlParam.reqPayAdd, postParam, response -> {
            if (complete != null)
                complete.onRequestComplete(response);
            LoadingDialog.closeLoadingDialog();
            if (!response.isOk()) {
                PToast.showShort(response.getMsg());
                return;
            }

            Pay pay = (Pay) response.getBaseData();
            if (payType == GoodsConstant.PAY_TYPE_ALIPAY) {
                new PayAlipayUtils().pay(pay.getUrl());
            } else {
                new PayWeixinUtils(App.getActivity()).pay(pay);
            }
        });
    }


    // ==============================================

    /**
     * 获取黑名单列表
     */
    public void getMyDefriends(int page, RequestComplete complete) {
        getUserRelation(page, new int[]{-4}, 10, complete);
    }

    /**
     * 获取我的好友列表，
     */
    public void getMyFriends(int page, RequestComplete complete) {
        getUserRelation(page, new int[]{1}, 100, complete);
    }

    /**
     * 获取聊过的人列表
     */
    public void reqHasChat(int page, RequestComplete complete) {
        HashMap<String, Object> param = new HashMap<>();
        param.put("is_vip", ModuleMgr.getCenterMgr().getMyInfo().getIsVip());
        param.put("limit", 10);
        param.put("offset", 10 * (page - 1));
        ModuleMgr.getHttpMgr().reqGetNoCacheHttp(UrlParam.getHasChat, param, complete);
    }

    /**
     * 查看我发起添加好友/ 拒绝我好友申请的列表
     */
    public void reqAddFriend(int page, RequestComplete complete) {
        getUserRelation(page, new int[]{-1, -3}, 10, complete);
    }

    /**
     * 获取用户关系列表，
     * <p>
     * 1：已成为好友  0: 没有记录， -1：申请成为好友  -2：聊过的人  -3：已拒绝  -4：黑名单  -5： 删除
     */
    private void getUserRelation(int page, int[] status_friend, int limit, RequestComplete complete) {
        HashMap<String, Object> param = new HashMap<>();
        param.put("status_friend", JSON.toJSONString(status_friend));
        param.put("limit", limit);
        param.put("offset", limit * (page - 1));
        ModuleMgr.getHttpMgr().reqGetNoCacheHttp(UrlParam.getUserRelation, param, complete);
    }

    /**
     * 获取好友申请列表，
     */
    public void getMyRequestFriends(int page, RequestComplete complete) {
        HashMap<String, Object> param = new HashMap<>();
        param.put("limit", 10);
        param.put("offset", 10 * (page - 1));
        ModuleMgr.getHttpMgr().reqGetAndCacheHttp(UrlParam.getMyRequestFriends, param, complete);
    }

    /**
     * 添加好友
     */
    public void setAddFriends(long tuid, RequestComplete complete) {
        setUserRelation(tuid, -1, complete);
    }

    /**
     * 接受好友请求
     */
    public void setMyFriends(long tuid, RequestComplete complete) {
        setUserRelation(tuid, 1, complete);
    }

    /**
     * 拒绝好友请求
     */
    public void setRefusedFriends(long tuid, RequestComplete complete) {
        setUserRelation(tuid, -3, complete);
    }

    /**
     * 加入黑名单
     */
    public void setBlackList(long tuid, RequestComplete complete) {
        setUserRelation(tuid, -4, complete);
    }

    /**
     * 移出黑名单
     */
    public void setRemoveBlackList(long tuid, RequestComplete complete) {
        setUserRelation(tuid, -5, complete);
    }

    /**
     * 移除好友
     */
    public void setRemoveFriendList(long tuid, RequestComplete complete) {
        setUserRelation(tuid, -6, complete);
    }

    /**
     * 改变好友关系 加好友、删除、加黑名单
     * <p>
     * 1：已成为好友  0: 没有记录， -1：申请成为好友  -2：聊过的人  -3：已拒绝  -4：黑名单  -5： 解除黑命单  -6： 删除关系
     */
    private void setUserRelation(long tuid, final int status_friend, final RequestComplete complete) {
        final HashMap<String, Object> param = new HashMap<>();
        param.put("uid_to", tuid);
        param.put("status_friend", status_friend);
        ModuleMgr.getHttpMgr().reqPostNoCacheHttp(UrlParam.setUserRelation, param, response -> {
            if (complete != null) {
                complete.onRequestComplete(response);
            }

            PToast.showShort(response.getMsg());
            if (!response.isOk()) {
                return;
            }
            MsgMgr.getInstance().sendMsg(MsgType.MT_Update_Friend, param);
        });
    }

    /**
     * 获取与指定用户关系状态
     * <p>
     * StatusFriend:
     * 黑名单 = -4
     * 已拒绝 = -3
     * 聊过的人 = -2
     * 申请好友 = -1
     * 没有记录（可加为好友） = 0
     * 好友 = 1
     */
    public void getUserRelation(long tuid, final UserRelationStatus listener) {
        getRelation(tuid, 2, response -> {
            if (listener != null) {
                listener.relationStatus(response.isOk(), response.getResponseObject().optInt("StatusFriend"));
            }
        });
    }

    public void getUserRelation(long tuid, final RequestComplete complete) {
        getRelation(tuid, 1, response -> {
            if (!response.isOk()) {
                PToast.showShort("获取好友关系失败，请稍后重试");
                return;
            }
            JSONObject jsonObject = response.getResponseObject();
            int status = jsonObject.optInt("StatusFriend");
            if (!canAdd(status)) {
                showAddToast(status);
                return;
            }
            if (complete != null) {
                complete.onRequestComplete(response);
            }
        });
    }

    /**
     * @param dt_status 方向： 默认为1 uid对uid_to的关系 = 1 uid_to对uid的关系 = 2
     */
    private void getRelation(long tuid, int dt_status, final RequestComplete complete) {
        HashMap<String, Object> param = new HashMap<>();
        param.put("uid_to", tuid);
        param.put("dt_status", dt_status);
        ModuleMgr.getHttpMgr().reqGetNoCacheHttp(UrlParam.setUserRelation, param, complete);
    }

    // 是否可以发起添加好友
    private boolean canAdd(int status) {
        return status == -3 || status == -2 || status == 0;
    }

    private void showAddToast(int status) {
        String statusMsg = "暂时无法添加该用户为好友";
        switch (status) {
            case -4:
                statusMsg = "您已被对方拉入黑名单，无法加好友";
                break;
            case -1:
                statusMsg = "好友申请中，无需重复添加";
                break;
            case 1:
                statusMsg = "您已是对方好友，无需重复添加";
                break;
        }
        PToast.showShort(statusMsg + " " + status);
    }

    /**
     * 提现
     *
     * @param type   提现类型 -1: 陪聊收益  -2: 邀请奖励
     * @param amount 提现金额
     */
    public void reqWithdraw(int type, String amount, RequestComplete complete) {
        HashMap<String, Object> postParams = new HashMap<>();
        postParams.put("type_amount", type);
        postParams.put("amount", amount);
        ModuleMgr.getHttpMgr().reqPostNoCacheHttp(UrlParam.reqWithdraw, postParams, complete);
    }

    /**
     * 现金收益列表
     */
    public void reqWalletDetail(int page, String month, RequestComplete complete) {
        reqEarnDetail(page, new int[]{-1, 1, 2}, month, complete);
    }

    /**
     * 邀请收益列表
     */
    public void reqInviteEarnDetail(int page, String month, RequestComplete complete) {
        reqEarnDetail(page, new int[]{-2, 3, 4, 9}, month, complete);
    }

    /**
     * 收益列表
     *
     * @param month 查询月份 默认本月 e.g. 查看5月份明细 201805
     */
    private void reqEarnDetail(int page, int[] type, String month, RequestComplete complete) {
        HashMap<String, Object> param = new HashMap<>();
        param.put("type_amounts", JSON.toJSONString(type));
        param.put("yearmonth", month);
        param.put("limit", 10);
        param.put("offset", 10 * (page - 1));
        ModuleMgr.getHttpMgr().reqGetNoCacheHttp(UrlParam.reqWalletDetail, param, complete);
    }

    /**
     * 钻石充值列表
     */
    public void reqDiamondList(RequestComplete complete) {
        HashMap<String, Object> param = new HashMap<>();
        param.put("limit", 50);
        ModuleMgr.getHttpMgr().reqGetAndCacheHttp(UrlParam.reqDiamondList, param, complete);
    }

    /**
     * 钻石明细列表
     *
     * @param month 查询月份 默认本月 e.g. 查看5月份明细 201805
     */
    public void reqDiamondDetail(int page, String month, RequestComplete complete) {
        HashMap<String, Object> param = new HashMap<>();
        param.put("yearmonth", month);
        param.put("limit", 10);
        param.put("offset", 10 * (page - 1));
        ModuleMgr.getHttpMgr().reqGetNoCacheHttp(UrlParam.reqDiamondDetail, param, complete);
    }

    /**
     * Vip特权列表
     */
    public void reqVipPrivilege(RequestComplete complete) {
        HashMap<String, Object> param = new HashMap<>();
        param.put("limit", 50);
        ModuleMgr.getHttpMgr().reqGetAndCacheHttp(UrlParam.reqVipPrivilege, param, complete);
    }

    /**
     * VIP充值列表
     */
    public void reqVipList(RequestComplete complete) {
        HashMap<String, Object> param = new HashMap<>();
        param.put("limit", 50);
        ModuleMgr.getHttpMgr().reqGetAndCacheHttp(UrlParam.reqVipList, param, complete);
    }

    /**
     * 邀请说明
     */
    public void reqInviteDeclare(RequestComplete complete) {
        HashMap<String, Object> param = new HashMap<>();
        param.put("limit", 50);
        ModuleMgr.getHttpMgr().reqGetAndCacheHttp(UrlParam.reqInviteDeclare, param, complete);
    }

    /**
     * 男性： 邀请收益兑换钻石
     */
    public void reqInviteExchange(int amount, RequestComplete complete) {
        HashMap<String, Object> param = new HashMap<>();
        param.put("amount", amount);
        ModuleMgr.getHttpMgr().reqPostNoCacheHttp(UrlParam.reqInviteExchange, param, complete);
    }

    /**
     * 邀请明细列表
     */
    public void reqInviteDetail(int page, RequestComplete complete) {
        HashMap<String, Object> param = new HashMap<>();
        param.put("limit", 10);
        param.put("offset", 10 * (page - 1));
        ModuleMgr.getHttpMgr().reqGetAndCacheHttp(UrlParam.reqInviteDetail, param, complete);
    }

    /**
     * 邀请赚钱-兑换钻石（用户当前金额及可兑换钻石数）
     */
    public void reqExchangeRule(RequestComplete complete) {
        ModuleMgr.getHttpMgr().reqGetAndCacheHttp(UrlParam.reqExchangeRule, null, complete);
    }

    /**
     * @return 获取礼品信息
     */
    public GiftsList getGiftLists() {
        if (giftLists == null) {
            giftLists = new GiftsList();
        }
        return giftLists;
    }

    /**
     * 请求礼物列表
     */
    public void requestGiftList(final GiftHelper.OnRequestGiftListCallback callback) {
        HashMap<String, Object> param = new HashMap<>();
        param.put("limit", 100);
        ModuleMgr.getHttpMgr().reqGetAndCacheHttp(UrlParam.getGiftLists, param, response -> {
            if (response.isOk()) {
                giftLists = (GiftsList) response.getBaseData();
                if (callback != null) {
                    callback.onRequestGiftListCallback(response.isOk());
                }
            }
        });
    }

    /**
     * 赠送
     */
    public void reqSendGift(long uidTo, int giftId, int num, RequestComplete complete) {
        HashMap<String, Object> param = new HashMap<>();
        param.put("uid_girl", uidTo);
        param.put("id_gift", giftId);
        param.put("num_gift", num);
        param.put("id_rec_chat", ModuleMgr.getRtcEnginMgr().getEngineConfig().mVcid);
        ModuleMgr.getHttpMgr().reqPostNoCacheHttp(UrlParam.reqSendGift, param, complete);
    }

    public RtcComplainReasons getComplainReasons() {
        if (complainReasons == null) {
            complainReasons = new RtcComplainReasons();
        }
        return complainReasons;
    }

    /**
     * 获取投诉列表
     */
    public void reqGetComplainReasons(final RequestComplete complete) {
        ModuleMgr.getHttpMgr().reqGetAndCacheHttp(UrlParam.reqGetComplainReasons, null, response -> {
            if (response.isOk()) {
                complainReasons = (RtcComplainReasons) response.getBaseData();
            }
            if (complete != null) {
                complete.onRequestComplete(response);
            }
        });
    }

    /**
     * 视频中投诉
     */
    public void reqAddComplaint(String reasons, String imgUrl, RequestComplete complete) {
        Map<String, Object> postParams = new HashMap<>();
        postParams.put("uid_to", config().mOtherId);
        postParams.put("id_rec_chat", config().mVcid);
        postParams.put("image", imgUrl);
        postParams.put("reasons", reasons);
        ModuleMgr.getHttpMgr().reqPostNoCacheHttp(UrlParam.reqAddComplaint, postParams, complete);
    }

    /**
     * 女性： 获取评分与奖励列表
     */
    public void reqSysAward(RequestComplete complete) {
        ModuleMgr.getHttpMgr().reqGetAndCacheHttp(UrlParam.reqSysAward, null, complete);
    }

    // ============================================================= 以下接口暂时保留 ===================================================================
    public ContactBean getContactBean() {
        return contactBean;
    }

    public void setContactBean(ContactBean contactBean) {
        this.contactBean = contactBean;
    }

    /**
     * 游戏交互-请求转发。接口回调data为String类型。[注意]：加密请求添加了新的header，若服务器无法处理，谨慎调用该方法
     *
     * @param requestType   请求方式（GET/POST）
     * @param requestUrl    请求完整地址，不会进行再次拼接
     * @param isEnc         是否为加密请求
     * @param requestObject 请求体参数
     * @param complete      请求回调
     */
    public void CMDRequest(String requestType, boolean isEnc, String requestUrl, Map<String, Object> requestObject, RequestComplete complete) {
        RequestParam requestParam = new RequestParam();
        if ("POST".equalsIgnoreCase(requestType)) {
            requestParam.setRequestType(RequestParam.RequestType.POST);
            if (requestObject != null) requestParam.setPost_param(requestObject);
        } else if ("GET".equalsIgnoreCase(requestType)) {
            requestParam.setRequestType(RequestParam.RequestType.GET);
            if (requestObject != null) requestParam.setGet_param(requestObject);
        }
        requestParam.setNeedEncrypt(isEnc);
        if (isEnc) requestParam.setHead_param(getEncHeaderMap());

        UrlParam urlParam = UrlParam.CMDRequest;
        urlParam.resetHost(requestUrl);
        requestParam.setUrlParam(urlParam);

        requestParam.setRequestCallback(complete);
        ModuleMgr.getHttpMgr().request(requestParam);
    }

    /**
     * @return 获取游戏调用时自定义的请求头：safe-request
     */
    public Map<String, String> getEncHeaderMap() {
        Map<String, String> headerParams = new HashMap<>();
        headerParams.put("Accept", "application/jx-json");
        headerParams.put("Content-Type", "application/jx-json");
        return headerParams;
    }

    /**
     * 请求一些在线配置信息
     */
    public void requestStaticConfig() {
        requestConfig();
    }

    /**
     * 请求服务器在线配置
     */
    private void requestConfig() {
        if (commonConfig == null) {
            commonConfig = new CommonConfig();
            commonConfig.parseJson(FileUtil.getFromAssets(App.getContext(), CommonConfig.STATIC_CONFIG_FILE));
        }
        Map<String, Object> requestParams = new HashMap<>();
        requestParams.put("platform", Constant.PLATFORM_TYPE);
        requestParams.put("ver", Constant.SUB_VERSION);//静态配置内容的版本本号(整数)
//        ModuleMgr.getHttpMgr().reqGetAndCacheHttp(UrlParam.staticConfig, requestParams, new RequestComplete() {
//            @Override
//            public void onRequestComplete(HttpResponse response) {
//                if (response.isOk()) {
//                    commonConfig.parseJson(response.getResponseString());
//                }
//            }
//        });
    }

    /**
     * @return 获取服务器静态配置对象
     */
    public CommonConfig getCommonConfig() {
        return commonConfig == null ? new CommonConfig() : commonConfig;
    }

    /**
     * 清除缓存
     */
    public void clearCache() {
        DirType.clearCache(App.getContext());
    }


    /**
     * 刷新充值是否成功
     */
    public void reqPayComplete(String order_no, RequestComplete complete) {
        Map<String, Object> postParams = new HashMap<>();
        postParams.put("order_no", order_no);
//        ModuleMgr.getHttpMgr().reqPostNoCacheHttp(UrlParam.refPayComplete, postParams, complete);
    }
}